<template>
	<div class="app-container">
		<div class="filter-container">
			<div class="fr" v-if="this.$store.state.user.matchAdminId === 8888 || this.$store.state.user.matchAdminId === 9999">
        <el-button v-permission="['SYS:MATCH:ADD']" class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleDelete(multipleSelection)" type="danger" icon="el-icon-delete">删除</el-button>
      </div>
    </div>
    
		<el-table class="tqd_table" :key='tableKey' :data="list" @selection-change="handleSelectionChange" v-loading="listLoading" border fit highlight-current-row style="width: 100%;">
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <el-table-column width="200px" label="比赛名称" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.matchName}}
        </template>
      </el-table-column>
      <!-- <el-table-column width="100px" align="center" label="赛事代码" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.matchCode}}</span>
        </template>
      </el-table-column> -->
      <el-table-column width="100px" align="center" label="比赛模式" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.pullData">简单模式</span>
          <span v-else>联网模式</span>
        </template>
      </el-table-column>
      <!-- <el-table-column width="80px" align="center" label="场地数量" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.placeCount}}</span>
        </template>
      </el-table-column> -->
      <el-table-column width="100" align="center" label="比赛时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.matchTime!=null">{{scope.row.matchTime | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column width="100" align="center" label="是否多锁" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.multiType">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>-->
     <!-- <el-table-column width="100" align="center" label="裁判人数" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.refereeType}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" class-name="small-padding fixed-width" v-if="this.$store.state.user.matchAdminId === 8888 || this.$store.state.user.matchAdminId === 9999">
        <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="addMatchProjectDialog(scope.row.id)">编辑比赛</el-button>
          <!-- <router-link :to="'/sys/match/referee?id='+scope.row.id">
            <el-button type="primary" size="mini">裁判管理</el-button>
          </router-link> -->
          <router-link :to="'/sys/match/admin/list?id='+scope.row.id">
            <el-button type="primary" size="mini">人员管理</el-button>
          </router-link>
          <router-link :to="'/sys/match/place?id='+scope.row.id">
          <el-button size="mini" type="primary">场地管理</el-button>
          </router-link>
          <!--<el-button v-if="!scope.row.pullData" size="mini" type="primary" @click="addMatchSchedule(scope.row.id,scope.row.multiType)">添加场次</el-button>
          <el-upload v-else class="myUpload" action="#" @click.native="setMatchId(scope.row.id)" :before-upload="beforeUpload" :show-file-list='false' :file-list="fileList">
            <el-button size="mini" type="primary">导入场次</el-button>
          </el-upload>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width" v-else>
        <template slot-scope="scope">
          <router-link :to="'/sys/match/admin/list?id='+scope.row.id+'&userId='+$store.state.user.matchAdminId">
            <el-button type="primary" size="mini">人员管理</el-button>
          </router-link>
          <router-link :to="'/sys/match/place?id='+scope.row.id">
            <el-button size="mini" type="primary">场地管理</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[15,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px" @open="getMatchScoreRuleList" :close-on-click-modal="false">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 100%; '>
        <el-form-item label="比赛名称" prop="matchName">
          <el-input v-model="temp.matchName"></el-input>
        </el-form-item>
        <el-form-item label="赛事代码" prop="matchCode">
          <el-input v-model="temp.matchCode"></el-input>
        </el-form-item>
        <el-form-item label="比赛时间" prop="matchTime">
          <el-date-picker v-model="temp.matchTime" type="date" value-format="yyyy-MM-dd 00:00:00" placeholder="请选择" :picker-options="pickerOptions0">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛模式">
          <el-switch v-model="temp.pullData" active-text="简单模式" @change="pullDataChanage(temp.pullData)" inactive-text="联网模式">
					</el-switch>
        </el-form-item>
        <el-form-item v-if="!temp.pullData" prop="pullDataUrl" label="数据地址">
					<el-input v-model="temp.pullDataUrl"></el-input>
        </el-form-item>
        <el-form-item prop="placeCount" label="场地数量">
          <el-input v-if="temp.pullData" :value="1" v-model.Number="temp.placeCount" type="number"  disabled="disabled"></el-input>
					<el-input v-else v-model.Number="temp.placeCount" type="number" @change="changePlaceCount(temp.placeCount)"></el-input>
        </el-form-item>
        <el-form-item prop="refereeType" label="裁判人数">
          <el-input v-if="temp.pullData" v-model.Number="temp.refereeType" value="3" type="number"   disabled="disabled" ></el-input>
          <el-input v-else v-model.Number="temp.refereeType" type="number"  ></el-input>
        </el-form-item>
        <!-- <el-form-item v-if="temp.pullData">
					<el-button size="mini">模板获取</el-button>
					<el-button size="mini">比赛导入</el-button>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <!-- <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button> -->
      </div>
    </el-dialog>
    <!-- 编辑比赛 -->
    <el-dialog title="编辑比赛" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :rules="rules" ref="editMatch" :model="editMatch" label-position="left" label-width="100px" style='width: 100%; '>
        <el-form-item label="比赛名称" prop="matchName">
          <el-input v-model="editMatch.matchName"></el-input>
        </el-form-item>
        <el-form-item label="比赛时间" prop="matchTime">
          <el-date-picker v-model="editMatch.matchTime" type="date" value-format="yyyy-MM-dd 00:00:00" placeholder="请选择" :picker-options="pickerOptions0">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="pullDataUrl" label="数据地址" v-if="!editMatch.pullData ">
					<el-input v-model="editMatch.pullDataUrl"></el-input>
        </el-form-item>
        <el-form-item prop="pullDataUrl" label="比赛项目" style="display: none">
        </el-form-item>
        <el-form-item v-for="(item,index) in editMatch.matchProject" :key="index" label="" label-width="0">
            <el-input v-model="item.projectName" style="width:370px;"></el-input><el-button style="float:right" @click.prevent="removeMathProject(index,[item.id])">删除</el-button>
        </el-form-item>
        <el-form-item label="" label-width="0" style="display: none">
          <el-button @click="addMatchProject">增加比赛项目</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMatchProjectItemList">确 定</el-button>
      </span>
      
    </el-dialog>

    <!-- 添加 -->
    <el-dialog title="添加场次" :visible.sync="addMatchScheduleDialog" width="950px" @open="getMatchScoreRuleList" :close-on-click-modal="false">
      <el-table class="tqd_table" :key='tableKey' :data="addSesionList" v-loading="listLoading" border fit highlight-current-row style="width: 100%;">
				<el-table-column align="center" label="比赛场地" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<!-- <el-input class="article-textarea"  style="width:110px;"  v-model="scope.row.matchPlaceId"></el-input>	 -->
            <el-select v-model="scope.row.matchPlaceId" placeholder="请选择" style="width:100px;">
							<el-option v-for="item in matchPlaceList" :key="item.id" :value="item.id" :label='item.placeName'></el-option>
						</el-select>					
					</template>
				</el-table-column>
				<el-table-column align="center" label="比赛类型代码" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-input class="article-textarea"  style="width:110px;"  v-model="scope.row.typeCode"></el-input>						
					</template>
				</el-table-column>
				<el-table-column align="center" label="拉取开始位置" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-input class="article-textarea"  style="width:110px;"  v-model="scope.row.rangeStart"></el-input>
					</template>
				</el-table-column>
				<el-table-column align="center" label="拉取结束位置" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-input class="article-textarea"  style="width:110px;"  v-model="scope.row.rangeEnd"></el-input>
					</template>
				</el-table-column>
				<el-table-column align="center" label="比赛类型" class-name="small-padding fixed-width">
					<template slot-scope="scope">
            <el-select v-model="scope.row.matchType" placeholder="请选择" style="width:100px;">
							<el-option value="2" label='对阵'></el-option>
              <el-option value="1" label='表演'></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column align="center" label="是否双品势" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.isTwo" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
            <el-button type="text" @click="scope.row.isTwo = !scope.row.isTwo">
              <span v-if="scope.row.isTwo">是</span>
              <span v-else>不是</span>
            </el-button>
					</template>
				</el-table-column>
				<el-table-column align="center" label="裁判规则">
					<template slot-scope="scope">
						<el-select v-model="scope.row.refereeType" placeholder="请选择" style="width:100px;">
							<el-option v-for="item in matchScoreRuleList" :key="item.id" :value="item.id" :label='item.name'></el-option>
						</el-select>
					</template>
				</el-table-column>
			</el-table>			
      <div slot="footer" class="dialog-footer">
        <el-button @click="addMatchScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="createScheduleByOnline">确定</el-button>
        <!-- <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button> -->
      </div>
    </el-dialog>
    <el-dialog title="删除" :visible.sync="deleteMatchScheduleDialog" width="350px" :close-on-click-modal="false">
      <el-form label-position="left"  label-width="100px" style='width: 100%; '>
        <el-form-item label="密码">
          <el-input v-model="currentPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteMatchScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmPasswordBtn">确定</el-button>
      </div>
    </el-dialog>
	</div>

</template>
<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import { getMatchList, saveMatch, getRefereeRule, getMatchInfo, updateMatch, deleteMatch } from '@/api/match'
import { deleteMatchProject } from '@/api/matchProject'
import { createScheduleByOnline, importSchedule } from '@/api/matchSchedule'
import { getMatchPlaceList } from '@/api/matchPlace'
import { getMatchScoreRuleList } from '@/api/matchScoreRule'
import { queryUserByPassword } from '@/api/user'
import waves from '@/directive/waves' // 水波纹指令
import { showMsg } from '@/utils'
export default {
  name: 'complexTable',
  directives: {
    waves, permission
  },
  data() {
    return {
      multipleSelection: [],
      uploadMatchId: null,
      fileList: [],
      addMatchScheduleDialog: false,
      deleteMatchScheduleDialog: false,
      addSesionList: [],
      matchPlaceList: [],
      listLoading: false,
      refereeRule: null,
      matchScoreRuleList: null,
      dialogVisible: false,
      ruleSetDialog: false,
      currentPassword: '',
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoadirefereeTypeng: true,
      listQuery: {
        // map: {},
        pageNum: 1,
        pageSize: 15
      },
      temp: {
        matchName: null, // 比赛名称
        matchTime: null, // 比赛时间
        pullDataUrl: null, // 数据地址
        placeCount: 1, // 场地数量
        matchCode: null, // 赛事代码
        refereeType: null, // 裁判人数
        multiType: false, // 是否多锁
        pullData: false, // 是否联网
        id: undefined
      },
      editMatch: {
        matchId: null,
        matchName: null, // 比赛名称
        matchTime: null, // 比赛时间
        pullDataUrl: null, // 数据地址
        matchProject: []// 比赛项目

      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        matchName: [{ required: true, message: '必填', trigger: 'blur' }],
        matchTime: [{ required: true, message: '必选', trigger: 'blur' }],
        matchCode: [{ required: true, message: '必填', trigger: 'blur' }],
        pullDataUrl: [{ required: true, message: '必填', trigger: 'blur' }],
        placeCount: [{ required: true, message: '必填', trigger: 'blur' }],
        refereeType: [{ required: true, message: '必选', trigger: 'change' }]
      },
      downloadLoading: false,
      loadSign: true,
      page: 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (var i in val) {
        this.multipleSelection.push(val[i].id)
      }
    },
    pullDataChanage: function(val) {
      if (val) {
        this.temp.placeCount = 1
        this.temp.refereeType = 3
      }
    },
    addSesionListItem(id, multiType) {
      this.addSesionList.push({
        matchId: id,
        typeCode: null,
        matchPlaceId: null,
        rangeStart: null,
        rangeEnd: null,
        matchType: null,
        multiType: multiType,
        refereeType: null,
        // pullData: null,
        isTwo: null
      })
    },
    addMatchSchedule(id, multiType) {
      getMatchPlaceList({ matchId: id }).then(response => {
        this.matchPlaceList = response.data.data
      })
      this.addSesionList = []
      for (var i = 0; i < 10; i++) {
        this.addSesionListItem(id, multiType)
      }
      this.addMatchScheduleDialog = true
    },
    addMatchProjectDialog(id) {
      this.editMatch.matchId = id
      this.editMatch.matchProject = [null]
      this.dialogVisible = true
      getMatchInfo({ matchId: this.editMatch.matchId }).then(res => {
        this.editMatch.matchId = res.data.data.id
        this.editMatch.matchName = res.data.data.matchName
        this.editMatch.matchTime = res.data.data.matchTime
        this.editMatch.pullDataUrl = res.data.data.pullDataUrl
        this.editMatch.pullData = res.data.data.pullData
        this.editMatch.matchProject = res.data.data.matchProjectList
      })
    },
    addRuleSetDialog(id) {
      this.ruleSetDialog = true
      this.ruleId = id
    },
    addMatchProject() {
      this.editMatch.matchProject.push({ id: null, matchId: this.editMatch.matchId, projectName: null })
    },
    removeMathProject(index, id) {
      if (id[0] === null) {
        this.editMatch.matchProject.splice(index, 1)
        return true
      }
      deleteMatchProject(id).then(res => {
        if (res.data.code === 0) {
          showMsg(res.data.message, 1)
          this.editMatch.matchProject.splice(index, 1)
        } else {
          showMsg(res.data.message, 2)
        }
      })
      this.editMatch.matchProject.splice(index, 1)
    },
    saveMatchProjectItemList() {
      var obj = {
        id: this.editMatch.matchId,
        matchName: this.editMatch.matchName, // 比赛名称
        matchTime: this.editMatch.matchTime, // 比赛时间
        pullDataUrl: this.editMatch.pullDataUrl, // 数据地址
        matchProjectList: this.editMatch.matchProject
      }
      updateMatch(obj).then(res => {
        if (res.data.code === 0) {
          this.dialogVisible = false
          showMsg(res.data.message, 1)
          this.getList()
        } else {
          showMsg(res.data.message, 2)
        }
      })
    },
    getReferee() {
      getRefereeRule().then(res => {
        this.refereeRule = res.data.data
      })
    },
    getMatchScoreRuleList() {
      getMatchScoreRuleList().then(response => {
        this.matchScoreRuleList = response.data.data
      })
    },
    changePlaceCount(count) {
      if (count < 1) {
        this.temp.placeCount = 1
      }
    },
    getList() {
      this.listLoading = true
      getMatchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        matchName: null, // 比赛名次
        matchTime: null, // 比赛时间
        pullDataUrl: null, // 数据地址
        placeCount: 1, // 场地数量
        matchCode: null, // 赛事代码
        refereeType: null, // 裁判人数
        multiType: false, // 是否多锁
        pullData: false, // 是否联网
        id: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.listLoading = true
          saveMatch(this.temp).then(res => {
            this.listLoading = false
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmPasswordBtn() {
      if (this.currentPassword === '') {
        showMsg('请输入密码', 2)
        return false
      }
      var obj = {
        userId: this.$store.state.user.matchAdminId,
        password: this.currentPassword
      }
      queryUserByPassword(obj).then(response => {
        if (response.data.data) {
          this.listLoading = true
          deleteMatch(this.multipleSelection).then(res => {
            if (res.data.code === 0) {
              showMsg(res.data.message, 1)
              this.getList()
              this.deleteMatchScheduleDialog = false
            } else {
              this.listLoading = false
              showMsg(res.data.message, 2)
            }
          })
        } else {
          showMsg('密码错误', 2)
        }
      })
    },

    handleDelete(idList) {
      if (idList.length === 0) {
        showMsg('请至少选择一条数据', 2)
        return false
      }
      this.deleteMatchScheduleDialog = true
    },
    createScheduleByOnline() {
      var obj = []
      for (var i in this.addSesionList) {
        if (this.addSesionList[i].matchPlaceId != null) {
          if (this.addSesionList[i].typeCode === null || this.addSesionList[i].rangeStart === null || this.addSesionList[i].rangeEnd === null || this.addSesionList[i].matchType === null || this.addSesionList[i].refereeType === null) {
            showMsg('提交的数据不完整', 2)
            return false
          }

          obj.push(Object.assign({}, this.addSesionList[i]))
        }
      }
      createScheduleByOnline(obj).then(res => {
        if (res.data.code === 0) {
          this.dialogFormVisible = false
          showMsg(res.data.message, 1)
        } else {
          showMsg(res.data.message, 2)
        }
      })
    },
    setMatchId(id) {
      this.uploadMatchId = id
    },
    beforeUpload: function(file) {
      console.log(file)
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error()
        showMsg('上传文件只能是 xls或xlsx 格式!', 2)
        return false
      }

      var fd = new window.FormData()
      fd.append('matchId', this.uploadMatchId)
      fd.append('file', file)
      importSchedule(fd).then(res => {
        if (res.data.code === 0) {
          this.dialogFormVisible = false
          showMsg(res.data.message, 1)
        } else {
          showMsg(res.data.message, 2)
        }
      })
      return false // 返回false不会自动上传
    }
  }
}
</script>
<style lang="scss" scoped>
.myUpload{
  display: -webkit-inline-box; 
}
.tags-view-item1{
  height: 100%;
  width: 100px;
  background: #5B9BD5;
  color: #ffffff;
}
.tab-text{
  height: 100%;
  display: -webkit-box;             /*flex弹性布局*/
  -webkit-box-align: center;
  -webkit-box-pack: center;
  font-size: 12pt;
}
</style>
